<?php

namespace app\admin\controller;

use app\common\lib\CusSession;
use think\Controller;
use think\facade\Request;

class Father extends Controller
{
    protected $_token_name = 'authorization';  // token名称
    protected $_login_key = 'auth_key';  //  session 保存的键名
    public function initialize()
    {
        $info = Request::header();
        if (isset($info[$this->_token_name]) && !empty($info[$this->_token_name])){
            CusSession::setId($info[$this->_token_name]);
        } else {
            CusSession::setId();
        }
        $user = CusSession::get($this->_login_key);
        # 允许不用访问的登陆模块
        $controller = request()->controller();
        switch (strtolower($controller)){
            case 'index' :
                # 允许访问的方法
                $action = request()->action();
                switch (strtolower($action)){
                    case 'login' :
                    case 'upload_picture' :
                        break;
                    default :
                        if(empty($user)){
                            $this->loginMessage($action);
                        }
                }
                break;
            default :
                if(empty($user)){
                    $this->loginMessage();
                }
        }

    }
    public function loginMessage(){
        $arr = [
            'success' => false,
            'messages' => '请登录',
        ];
        header('HTTP/1.1 401 Unauthorized');
        header('Status:401 Unauthorized');
        header('Content-Type: application/json; charset=UTF-8');
        exit(json_encode($arr));
    }
    public function page($page ,$size,$success,$message,$table){
        $return = [
            'data' => '',
            'success' => $success,
            'messages' => $message,
            'page' =>$page,
            'size' => $size
        ];
        $data2 = model($table)->order('weight asc,update_time desc')->paginate($size, false, [
            'page' => $page,
            'var_page' => 'page'
        ]);
        $data = $data2->toArray();

        if ($page>$data['last_page']) {
            $data = model('Classes')->order('weight asc,update_time desc')->paginate($size, false, [
                'page' => $data['last_page'],
                'var_page' => 'page'
            ]);
            $data = $data->toArray();
            $return['page'] = $data['last_page'];
        }
        $classes = $data['data'];
        foreach ($classes as $k=>$v){

            $classes[$k]['count'] = Db::table('articles')->where('class_id',$v['id'])->count();

        }
        $return['data'] = $classes;
        $return['total'] = $data['total'];

        $return['page'] = $data['current_page'];
        return $return;
    }
}
